package com.mywork.mvpkodeingithub.repository

import com.mywork.mvpkodeingithub.data.api.GithubApi
import com.mywork.mvpkodeingithub.data.cache.GithubCache
import com.mywork.mvpkodeingithub.data.response.Repo
import com.mywork.mvpkodeingithub.data.response.User
import com.mywork.mvpkodeingithub.net.RetrofitFactory
import io.reactivex.Observable
import io.rx_cache2.DynamicKey
import io.rx_cache2.EvictDynamicKey
import io.rx_cache2.Reply
import io.rx_cache2.internal.RxCache
import io.victoralbertos.jolyglot.GsonSpeaker
import org.kodein.di.Kodein
import org.kodein.di.generic.instance
import java.io.File


class GithubRepository(kodein: Kodein) {

    private val githubCache: GithubCache

    //Inject
    val githubService: GithubApi

    //Inject
    val cacheDir: File by kodein.instance()

    init {
        githubCache = RxCache.Builder()
            .setMaxMBPersistenceCache(Int.MAX_VALUE)//设置本地缓存的最大容量,单位为MB，如果没设置则默认为100MB
            .persistence(cacheDir, GsonSpeaker())
            .using(GithubCache::class.java)

        githubService = RetrofitFactory.create(GithubApi::class.java)

    }

    /*fun getUsers(lastIdQueried: Int, perPage: Int): Observable<List<User>> {
        return githubService.getUsers(lastIdQueried, perPage)
    }*/

    fun getUsers(idLastUserQueried: Int, update: Boolean): Observable<Reply<List<User>>> {
        return githubCache.getUsers(
            githubService.getUsers(idLastUserQueried, PAGE_COUNT), DynamicKey(idLastUserQueried), EvictDynamicKey(update)
        )
    }

    /*fun getRepos(userName: String): Observable<List<Repo>> {
        return githubService.getRepos(userName)
    }*/

    fun getRepos(userName: String, update: Boolean): Observable<Reply<List<Repo>>> {
        return githubCache.getRepos(
            githubService.getRepos(userName), DynamicKey(userName), EvictDynamicKey(update)
        )
    }

    companion object {
        const val  PAGE_COUNT:Int=20
    }


}
